package edu.zju.gis.dbfg.fileserver.controller;

import edu.zju.gis.dbfg.common.Page;
import edu.zju.gis.dbfg.common.Result;
import edu.zju.gis.dbfg.common.base.BaseController;
import edu.zju.gis.dbfg.fileserver.config.BackendFileSystemConfiguration;
import edu.zju.gis.dbfg.fileserver.model.LoaderMonitor;
import edu.zju.gis.dbfg.fileserver.model.search.ConstructedDatasetSearch;
import edu.zju.gis.dbfg.fileserver.model.vo.MonitorInfo;
import edu.zju.gis.dbfg.fileserver.operator.FileOperator;
import edu.zju.gis.dbfg.fileserver.service.ConstructedDatasetService;
import edu.zju.gis.dbfg.fileserver.service.LoaderMonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Path;
import java.util.List;

@CrossOrigin
@Controller
@RequestMapping("/dataset/monitor")
public class PersonalDatasetController extends BaseController<LoaderMonitor, LoaderMonitorService, String, ConstructedDatasetSearch> {

    @Autowired
    private FileOperator fileOperator;
    @Autowired
    private ConstructedDatasetService constructedDatasetService;
    @Autowired
    private BackendFileSystemConfiguration fileSetting;

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    @ResponseBody
    public Result selectByPage(@SessionAttribute("userId") String userId, Page page) {
        Page<MonitorInfo> monitors = this.service.selectByPage(userId, page);
        return Result.success().setBody(monitors);
    }

    @RequestMapping(value = "/allFinish", method = RequestMethod.GET)
    @ResponseBody
    public Result selectByPageFinish(@SessionAttribute("userId") String userId, Page page) {
        Page<MonitorInfo> monitors = this.service.selectByPageFinish(userId, page);
        return Result.success().setBody(monitors);
    }

    @RequestMapping(value = "/log/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result selectLogById(@PathVariable String id) {
        LoaderMonitor result = this.service.select(id);
        if (result != null) {
            if (!result.getStatus().equals("Finish")) {
                return Result.error().setMessage("数据正在录入，暂时不能查看日志");
            } else {
                String logs = result.getLogs();
                if (logs.length() > 10000) {
                    logs = logs.substring(0, 10000) + "........(查看完整日志请下载)";
                }
                return Result.success().setBody(logs);
            }
        } else
            return Result.error().setMessage("未查询到结果");
    }

    @RequestMapping(value = "/logDownload", method = RequestMethod.GET)
    @ResponseBody
    public Result downloadLogById(String id, HttpServletResponse response, String name) {
        LoaderMonitor result = this.service.select(id);
        if (!result.getStatus().equals("Finish")) {
            return Result.error().setMessage("数据正在录入，暂时不能下载日志");
        } else {
            if (result != null) {
//           String logTempPath="F:\\userSpace\\logs\\1.txt";
                String logTempPath = fileSetting.getLogTemSpace() + name + ".txt";
                FileWriter fwriter = null;
                try {
                    // true表示不覆盖原来的内容，而是加到文件的后面。若要覆盖原来的内容，直接省略这个参数就好
                    fwriter = new FileWriter(logTempPath);
                    fwriter.write(result.getLogs());
                } catch (IOException ex) {
                    return Result.error().setMessage("下载失败");
//                ex.printStackTrace();
                } finally {
                    try {
                        fwriter.flush();
                        fwriter.close();
                        if (!fileOperator.exist(logTempPath))
                            return Result.error().setMessage("Path is not exist.");
                        if (fileOperator.isDirectory(logTempPath))
                            return Result.error().setMessage("Path is not file.");
                        fileOperator.download(logTempPath, response);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        return Result.error().setMessage("下载失败");
                    }
                }
                return Result.success().setMessage("下载成功");
            } else
                return Result.success().setMessage("未得到相应内容");
        }
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result selectById(@PathVariable String id) {
        LoaderMonitor result = this.service.watchStatus(id);
        if (result != null)
            return Result.success().setBody(result);
        else
            return Result.success().setMessage("未查询到结果");
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result deleteById(@PathVariable String id) {
        int result = this.service.deleteByPrimaryKey(id);
        int result2 = constructedDatasetService.deleteByPrimaryKey(id);
//        MonitorInfo result = this.service.watchStatus(id);
        if (result == 1 && result2 == 1)
            return Result.success().setMessage("删除入库任务成功");
        else
            return Result.success().setMessage("删除入库任务失败");
    }
}
